package com.das.mechanic_base.mvp.view.create;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.res.ResourcesCompat;
import androidx.viewpager.widget.ViewPager;

import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.AloneDelSelectedBean;
import com.das.mechanic_base.bean.create.SaveWorkSuccessBean;
import com.das.mechanic_base.bean.create.SelectWorkBean;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.bean.main.DoneDetectionBean;
import com.das.mechanic_base.mvp.contract.create.X3SelectWorkContract;
import com.das.mechanic_base.mvp.presenter.create.X3SelectWorkPresenter;
import com.das.mechanic_base.mvp.view.create.fragment.X3ServicePagerAdapter;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ViewPagerBind;
import com.das.mechanic_base.widget.X3AloneFastSelectDialog;
import com.das.mechanic_base.widget.X3BottomAlreadySelectDialog;
import com.das.mechanic_base.widget.X3BottomStaffDialog;
import com.kproduce.roundcorners.RoundButton;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static androidx.fragment.app.FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT;

public class SelectWorkActivity extends X3BaseActivity<X3SelectWorkPresenter> implements X3SelectWorkContract.View, TextWatcher, X3BottomStaffDialog.IOnSaveWorkBase, X3BottomAlreadySelectDialog.IOnSelectWorkLisener, X3AloneFastSelectDialog.IBtnClick {

    @BindView(R2.id.rl_header)
    RelativeLayout rl_header;
    @BindView(R2.id.tb_layout)
    MagicIndicator tb_layout;
    @BindView(R2.id.vp_main)
    ViewPager vp_main;
    @BindView(R2.id.v_top)
    View v_top;
    @BindView(R2.id.edt_search)
    EditText edt_search;
    @BindView(R2.id.iv_clean)
    ImageView iv_clean;
    @BindView(R2.id.fl_empty)
    FrameLayout fl_empty;
    @BindView(R2.id.rl_bottom)
    RelativeLayout rl_bottom;
    @BindView(R2.id.tv_num)
    TextView tv_num;
    @BindView(R2.id.rb_btn)
    RoundButton rb_btn;
    @BindView(R2.id.v_divider)
    View v_divider;

    private long receiveBaseId;
    private boolean isDetection;

    private List<SelectWorkBean> mList = new ArrayList<>();
    private X3ServicePagerAdapter pagerAdapter;
    private X3BottomStaffDialog staffDialog;

    private List<SelectWorkBean.ServiceBaseEntityBean> sList;
    private boolean isSdk;

    private X3BottomAlreadySelectDialog x3BottomAlreadySelectDialog;

    private X3AloneFastSelectDialog x3AloneFastSelectDialog;

    boolean fastSelectCancle ;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_work;
    }

    @Override
    protected void initView() {

        X3StatusBarUtil.darkMode(this);

        setSwipeBackEnable(false);

        rl_header.setPadding(0,X3StatusBarUtil.getStatusBarHeight(this),0,0);

        isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
        receiveBaseId = getIntent().getLongExtra("receiveBaseId", 0L);
        isDetection = getIntent().getBooleanExtra("isDetection", false);

        sList = new ArrayList<>();
        initTabLayout();
        requestServiceList("");
        edt_search.addTextChangedListener(this);

        rb_btn.setBackgroundResource(R.drawable.x3_bg_btn_disable_status);

        if (isDetection){
            rl_bottom.setVisibility(View.GONE);
            v_divider.setVisibility(View.GONE);
        }

    }

    /**
     * 获取项目列表
     * @param keyWord
     */
    private void requestServiceList(String keyWord) {
        Map<String,Object> map = new HashMap<>();
        map.put("ifDetection",isDetection);
        map.put("keyWord",keyWord);
        map.put("receiveBaseId",receiveBaseId);
        if (mPresenter != null) {
            showLoading("");
            mPresenter.getServiceList(map);
        }
    }

    @Override
    protected X3SelectWorkPresenter createPresenter() {
        return new X3SelectWorkPresenter();
    }

    @OnClick({R2.id.iv_back,R2.id.iv_clean,R2.id.rb_btn,R2.id.rrl_tip})
    public void onViewClick(View view) {
        if (view.getId() == R.id.iv_back) {
            finish();

        }else if (view.getId() == R.id.iv_clean) {
            edt_search.setText("");
        }else if (view.getId() == R.id.rb_btn) {
            boolean enable = false;
            if (rb_btn.getTag() != null ){
                String tag = (String) rb_btn.getTag();
                if ("enable".equals(tag)){
                    enable = true;
                }
            }
            if (!enable){
                return;
            }
            // 下单
            staffDialog = new X3BottomStaffDialog(this);
            staffDialog.setiOnSaveWork(this);
            staffDialog.show();
//            staffDialog.setOnDismissListener(dialogInterface -> finish());
            staffDialog.startStaffWork(receiveBaseId,sList,isDetection);

        } else if (view.getId() == R.id.rrl_tip){
            x3BottomAlreadySelectDialog = new X3BottomAlreadySelectDialog(this,sList,this);
            x3BottomAlreadySelectDialog.show();
        }
    }

    private void initTabLayout() {
        CommonNavigator tbNavigator = new CommonNavigator(this);
        tbNavigator.setScrollPivotX(0.65f);
        tbNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return X3StringUtils.isListEmpty(mList) ? 0 : mList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView titleView = new SimplePagerTitleView(context);
                titleView.setText(mList.get(index).serviceCategoryValue);
                titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
                titleView.setTypeface(ResourcesCompat.getFont(context,R.font.pingfan_bold));
                titleView.setNormalColor(Color.parseColor("#b1b3bd"));
                titleView.setSelectedColor(Color.parseColor("#333333"));
                titleView.setOnClickListener(v -> vp_main.setCurrentItem(index));
                return titleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(X3ScreenUtils.dipToPx(3,context));
                indicator.setLineWidth(X3ScreenUtils.dipToPx(16,context));
                indicator.setRoundRadius(X3ScreenUtils.dipToPx(3,context));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(Color.parseColor("#0077ff"));
                return indicator;
            }
        });
        tb_layout.setNavigator(tbNavigator);
        X3ViewPagerBind.bind(tb_layout,vp_main);
    }

    @Override
    public void getServiceListSuccess(List<SelectWorkBean> mList,String keyWord) {
        hideLoading();
        if (X3StringUtils.isListEmpty(mList)) {
            mList = new ArrayList<>();
        }
        this.mList = mList;
        vp_main.setVisibility(View.VISIBLE);
        tb_layout.setVisibility((mList.size() == 0 || mList.size() == 1) ? View.GONE : View.VISIBLE);
        v_top.setVisibility((mList.size() == 0 || mList.size() == 1) ? View.GONE : View.VISIBLE);
        tb_layout.getNavigator().notifyDataSetChanged();
        pagerAdapter = new X3ServicePagerAdapter(getSupportFragmentManager(),BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        pagerAdapter.isDetection = isDetection;
        vp_main.setAdapter(pagerAdapter);
        pagerAdapter.changeServicePager(mList);
        tb_layout.onPageSelected(0);

        addEmptyView(mList);
        if (!fastSelectCancle){
            mPresenter.getDoneDetectionList(receiveBaseId);
        }
    }

    @Override
    public void getServiceListFail(){
        hideLoading();
    }

    @Override
    public void getDoneDetectionListSuccess(List<DoneDetectionBean> mList) {
        if(!isDetection && mList != null && mList.size() > 0 && (staffDialog==null || !staffDialog.isShowing())){
            x3AloneFastSelectDialog = new X3AloneFastSelectDialog(SelectWorkActivity.this,mList);
            x3AloneFastSelectDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    fastSelectCancle = true;
                }
            });
            x3AloneFastSelectDialog.setiBtnClick(this);
            x3AloneFastSelectDialog.show();
        }
    }

    @Override
    public void getDoneDetectionListFail() {

    }

    /**
     * 获取已经选中的服务项目
     * @return
     */
    public List<SelectWorkBean.ServiceBaseEntityBean> getServiceVariantBeanList () {
        if (isDetection) {
            return new ArrayList<>();
        }
        return sList;
    }

    /**
     * 是否展示空白布局
     * @param mList
     */
    private void addEmptyView(List<SelectWorkBean> mList) {
        if (!X3StringUtils.isListEmpty(mList)) {
            fl_empty.setVisibility(View.GONE);
            return;
        }
        tb_layout.setVisibility(View.GONE);
        v_top.setVisibility(View.GONE);
        vp_main.setVisibility(View.GONE);
        fl_empty.setVisibility(View.VISIBLE);
        fl_empty.removeAllViews();
        View emptyView = View.inflate(this,R.layout.x3_empty_layout,null);
        TextView tv_empty = emptyView.findViewById(R.id.tv_empty);
        ImageView iv_empty = emptyView.findViewById(R.id.iv_empty);
        iv_empty.setImageResource(R.mipmap.x3_no_search_result_icon);
        tv_empty.setText(getString(R.string.x3_no_search_data));
        LinearLayout.LayoutParams emptyLayout = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        emptyLayout.topMargin = X3ScreenUtils.dipToPx(120, this);
        fl_empty.addView(emptyView,emptyLayout);
    }

    /**
     * 开始下单
     * @param serviceBean
     * @param isAdd
     */
    public void addWorkToStaff(SelectWorkBean.ServiceBaseEntityBean serviceBean, boolean isAdd) {
        if (serviceBean == null) {
            return;
        }
        if (isDetection) {
            staffDialog = new X3BottomStaffDialog(this);
            staffDialog.setiOnSaveWork(this);
            staffDialog.show();
            staffDialog.setOnDismissListener(dialogInterface -> finish());
            List<SelectWorkBean.ServiceBaseEntityBean> variantEntityBeans = new ArrayList<>();
            variantEntityBeans.add(serviceBean);
            staffDialog.startStaffWork(receiveBaseId,variantEntityBeans,isDetection);
            return;
        }
        // 需要对集合做加减处理
        if (isAdd) {
            sList.add(serviceBean);
        }else {
            sList.remove(serviceBean);
        }
        tv_num.setVisibility(sList.size() <= 0 ? View.GONE : View.VISIBLE);
        tv_num.setText(sList.size()+"");
        rbBtnStatus();
    }


    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        String content = editable.toString();
        iv_clean.setVisibility(X3StringUtils.isEmpty(content) ? View.GONE : View.VISIBLE);
        requestServiceList(content);
    }

    @Override
    public void iOnSaveWorkSuccess(SaveWorkSuccessBean successBean,boolean isDetection) {
        if (successBean == null) {
            return;
        }
        // 跳转到安排施工成功页面
        if (!isSdk) {
            Bundle bundle = new Bundle();
            bundle.putString("title","创建施工单成功");
            bundle.putBoolean("isDark",true);
            long workBaseId = successBean == null ? 0 : successBean.workBaseId;
            String serviceCategoryName = successBean == null ? "" : successBean.serviceCategoryName;
            bundle.putString("path", X3Constent.SAVE_WORK_SUCCESS + "?id=" + receiveBaseId + "&workBaseId=" + workBaseId + "&serviceCategoryName=" + serviceCategoryName);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);
        }
        DeleteFriends deleteFriends = new DeleteFriends("Create_Work_Order",isDetection);
        EventBus.getDefault().post(deleteFriends);
        finish();
    }

    @Override
    public void iOnRefreshData() {

    }

    @Override
    public void iOnSelectWork(SelectWorkBean.ServiceBaseEntityBean serviceBean, boolean isDel) {
        if (isDel){
            sList.clear();
        }else{
            sList.remove(serviceBean);
        }
        refreshSelectUI();
    }

    private void refreshSelectUI(){
        tv_num.setVisibility(sList.size() <= 0 ? View.GONE : View.VISIBLE);
        tv_num.setText(sList.size()+"");
        EventBus.getDefault().post(new AloneDelSelectedBean());
        rbBtnStatus();
    }

    private void rbBtnStatus(){
        if (sList.size()>0){
            rb_btn.setTag("enable");
            rb_btn.setBackgroundResource(R.drawable.x3_bg_btn_status);
        }else{
            rb_btn.setBackgroundResource(R.drawable.x3_bg_btn_disable_status);
            rb_btn.setTag("");
        }
    }

    @Override
    public void iBtnAffirmClick(List<DoneDetectionBean> mFastList) {

        List<DoneDetectionBean.ServiceInfoVoListDTO> tmpList = new ArrayList<>();
        for (DoneDetectionBean bean : mFastList){
            if (bean.isSelect && bean.getServiceInfoVoList() != null && bean.getServiceInfoVoList().size() > 0){
                tmpList.addAll(bean.getServiceInfoVoList());
            }
        }

        if (mList != null){
            for (int i = 0; i<mList.size(); i++){
                List<SelectWorkBean.ShopCategoryEntityBean> shopCategoryEntityList = mList.get(i).shopCategoryEntityList;
                for (int j = 0; j < shopCategoryEntityList.size();j++){
                    List<SelectWorkBean.ServiceBaseEntityBean> serviceBaseEntityList = shopCategoryEntityList.get(j).serviceBaseEntityList;
                    for (SelectWorkBean.ServiceBaseEntityBean bean : serviceBaseEntityList){
                        for (DoneDetectionBean.ServiceInfoVoListDTO dto : tmpList){
                            if (dto.getSn().equals(bean.sn) && !sList.contains(bean)){
                                sList.add(bean);
                            }
                        }
                    }
                }
            }
            refreshSelectUI();
        }
    }
}